package com.ha.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ha.constant.MessageConstant;
import com.ha.constant.PasswordConstant;
import com.ha.constant.StatusConstant;
import com.ha.context.BaseContext;
import com.ha.dto.EmployeeDTO;
import com.ha.dto.EmployeeLoginDTO;
import com.ha.dto.EmployeePageQueryDTO;
import com.ha.dto.PasswordEditDTO;
import com.ha.entity.Employee;
import com.ha.exception.AccountLockedException;
import com.ha.exception.AccountNotFoundException;
import com.ha.exception.PasswordErrorException;
import com.ha.mapper.EmployeeMapper;
import com.ha.result.PageResult;
import com.ha.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * ClassName: EmployeeServiceImpl
 * Package: com.ha.service.impl
 * Description:
 *
 * @Author 那啥啥
 * @Create 2024/3/31  17:11
 * @Version 1.0
 */
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //查询数据库
       Employee employee =  employeeMapper.getByUsername(username);
//不存在用户
       if(employee == null ){
           throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
       }

       //存在账户，密码用md5加密
       password = DigestUtils.md5DigestAsHex(password.getBytes());
//密码不相等
       if(!password.equals(employee.getPassword())){

           throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
       }
       //密码相等，账号已锁定
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
//全满足后返回实体
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //设置账号状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置创建时间和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置当前记录创建人id
        //动态获取id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.insert(employee);
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询,动态添加limit 和计算 来实现查询,基于拦截器
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> result = page.getResult();
        return new PageResult(total,result);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee =
                Employee.builder().
                        status(status)
                        .id(id)
                        .build();
       /* employee.setId(id);
        employee.setStatus(status);*/
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee =   employeeMapper.getById(id);
        employee.setPassword("*****");
        return employee;
    }
    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        String psd1 = passwordEditDTO.getOldPassword();
        String psd2 = passwordEditDTO.getNewPassword();
        if(psd1.equals(psd2)){
            throw new PasswordErrorException("新旧密码不能一样");
        }
        Long empId = BaseContext.getCurrentId();
        Employee employee = employeeMapper.getById(empId);
        if(DigestUtils.md5DigestAsHex(psd1.getBytes()).equals(employee.getPassword())){
            Employee employee1 = Employee.builder()
                    .id(empId)
                    .password(DigestUtils.md5DigestAsHex(psd2.getBytes()))
                    .build();
            employeeMapper.update(employee1);
        }else {
            throw new PasswordErrorException("原密码不正确");
        }
    }
}
